var express = require('express');
var router = express.Router();
var open = require('../../utils/mgdb').open;
var bcrypt = require('../../utils/bcrypt');
var jwt = require('../../utils/jwt')

router.post('/', function(req, res, next) {

  console.log('login')

  //获取username,password
  let {username,password} = req.body;
  
  //设定必传参数
  if(!username || !password) {
    res.send({
      err:1,
      msg:'用户名密码为必传参数'
    })
    return;
  }
  
  //兜库 open
  open({
    collectionName:'user'
  }).then(
    ({collection,client})=>{
      collection.find({username}).toArray((err,result)=>{
        if(err){
          res.send({err:1,msg:'集合操作失败',mess:err})
          client.close()
        }else{
          //校验username存在
          if(result.length>0){
            //校验密码  解密 对比
            if(bcrypt.compareSync(password,result[0].password)){
              // 失败 || 成功（生成token
              let token = jwt.sign({username,_id:result[0]._id});

              // delete result[0].username;
              //  delete result[0].password;

              res.send({err:0,msg:'登陆成功',data:result[0],token})

              client.close()
              
            }else{
              res.send({err:1,msg:'用户名或者密码不存在'})
              client.close()
            }
          }else{
            res.send({err:2,msg:'用户名或者密码不存在'})
            client.close()
          }
        }
      })
    }
  ).catch(
    err=>res.send({
      err:1,
      msg:'库链接失败'
    })
  )


});

module.exports = router;
